package cn.fansunion.photo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class BaseController {

	public void returnJsonObject(HttpServletResponse response,
			JSONObject jsonObject) {
		String jsonString = JSON.toJSONString(jsonObject,
				SerializerFeature.DisableCircularReferenceDetect);
		returnJsonString(response, jsonString);
	}

	public void returnObjectJsonString(HttpServletResponse response,
			Object object) {
		String jsonStr = JSONObject.toJSONString(object);

		returnJsonString(response, jsonStr);
	}

	public static void returnJsonString(HttpServletResponse response,
			String content) {
		returnMessage(response, content);
	}

	public static void returnMessage(HttpServletResponse response,
			String content) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		PrintWriter pWriter = null;
		try {
			pWriter = response.getWriter();
			pWriter.write(content);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (pWriter != null) {
				pWriter.flush();
				pWriter.close();
			}
		}
	}

	protected void jsonSucceed(HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", 1);
		returnJsonObject(response, jsonObject);
	}

}
